package com.xxx.io;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author blijojo
 * @date 2021/7/12 12:53
 * 传统IO编程-服务器端
 */
public class IoServer {

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8000);
        while (true) {
            // (1) 阻塞方法获取新的连接
            Socket socket = serverSocket.accept();
            new Thread(() -> {
                String name = Thread.currentThread().getName();
                InputStream is;
                try {
                    is = socket.getInputStream();
                    byte[] data = new byte[1024];
                    int len;
                    while ((len = is.read(data)) != -1) {
                        System.out.println("线程" + name + ":" + new String(data, 0, len));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }).start();
        }
    }

}
